<template>
    <div class="page">
        <x-header :left-options="{showBack: true,backText:'购买课程'}" class="headerBox"></x-header>
        <div class="buyTitle">课程</div>
        <input type="hidden" id="courseId" :value="courseInfo.id">
        <input type="hidden" id="userId" :value="162">
        <div class="buyList">
            <div class="buyList_img">
                <img :src="courseInfo.largePicture"/>
            </div>
            <div class="buyList_con">
                <div>{{courseInfo.title}}</div>
                <!--                <div>讲师：{{teacher}}</div>-->
            </div>
        </div>
        <div class="buyTitle">支付方式</div>
        <!-- 优惠券 -->
        <div class="buyWay">
            <img :src="payIcon"/>
            <div>{{payType}}</div>
            <img :src="paySelect"/>
        </div>
        <router-link :to="{name:'myCoupon',query:{courseId:courseInfo.id}}" class="setList">
            <div class='buyTicket'>
                <div>添加优惠券/邀请码</div>
                <img src="../assets/images/unfold01.png"/>
            </div>
        </router-link>
        <!--         价格 -->
        <div class="buyPrice">
            <div class="buyPrice_orig dis_flex">
                <div>原价</div>
                <div class="buyPrice_auto">￥{{courseInfo.price/100}}</div>
            </div>
            <div class="buyPrice_priv dis_flex" style="display: none">
                <img src="../assets/images/onlytime01.png"/>
                <div class="buyPrice_auto">-￥{{courseInfo.price/100}}</div>
            </div>
            <div class="buyPrice_money dis_flex">
                <div>应付金额</div>
                <div class="buyPrice_auto">￥{{price}}</div>
            </div>
        </div>
        <!-- 立即支付 -->
        <!--        <router-link to="/buySuccess" class="buyNow">立即支付</router-link>-->
        <swiper-item class="buyNow" :style="status==true?'background-color:red':'background-color:gray'">
            <div aria-disabled="false" @click="toapply()">
                立即支付
            </div>
        </swiper-item>
    </div>
</template>

<script>
    import {XHeader} from "vux";
    import {courseDetail, createPayRecord} from '@/api/index/index';
    import {addStudy} from '@/api/index/study';
    import store from "../store/store"


    export default {
        components: {
            XHeader
        },
        data() {
            return {
                courseId: '',
                courseImg: require('../assets/images/course02.png'),
                courseTitle: '零基础直达流利口语中级',
                teacher: 'Candy',
                payIcon: require('../assets/images/wechartlogo.png'),
                payType: '微信支付',
                paySelect: require('../assets/images/select011.png'),
                original: '499',
                discount: '100',
                price: 0,
                courseInfo: [],
                status: true,
                refresh: true,

            }
        },
        created() {
            let id = this.$route.query.id;
            courseDetail(id, this.$store.state.user.id).then(res => {
                this.courseInfo = res.data.data.courseInfo;
                this.courseId = res.data.data.courseInfo.id;
                if (this.$store.state.user.rate >= (res.data.data.courseInfo.price / 100)) {
                    console.log(this.$store.state.user.rate)
                    console.log(res.data.data.courseInfo.price)
                    this.price = res.data.data.courseInfo.price / 100;
                } else {
                    console.log(this.$store.state.user.rate)
                    console.log(res.data.data.courseInfo.price)
                    if (this.$store.state.user.rate == undefined) {
                        var rate = 0;
                    } else {
                        var rate = this.$store.state.user.rate;
                    }
                    this.price = (res.data.data.courseInfo.price / 100) - rate
                }
            }).catch(err => {
                console.log(err)
            });
            this.share(id);
            // this.getConfig();


        },
        methods: {
            getUrlParam(paraName) {
                var url = document.location.toString();
                var arrObj = url.split("?");

                if (arrObj.length > 1) {
                    var arrPara = arrObj[1].split("&");
                    var arr;

                    for (var i = 0; i < arrPara.length; i++) {
                        arr = arrPara[i].split("=");

                        if (arr != null && arr[0] == paraName) {
                            return arr[1];
                        }
                    }
                    return "";
                } else {
                    return "";
                }
            },

            toapply() {
                console.log(this.status)
                if (this.status) {
                    var code = this.getUrlParam("code"); //是否存在code
                    var tenantId = this.$store.state.user.tenantId;
                    var userId = this.$store.state.user.id;
                    var courseId = this.courseId;
                    console.log(this.$store.state.user.rate);
                    console.log(this.courseInfo.price / 100);
                    if (this.$store.state.user.rate >= this.courseInfo.price / 100) {
                        var price = this.courseInfo.price / 100;
                    } else {
                        if (this.$store.state.user.rate == undefined) {
                            var rate = 0;
                        } else {
                            var rate = this.$store.state.user.rate;
                        }
                        var price = (this.courseInfo.price / 100) - rate
                    }

                    if (code != '') {
                        createPayRecord(courseId, tenantId, userId, code, price).then(res => {
                            if (typeof WeixinJSBridge == "undefined") {
                                if (document.addEventListener) {
                                    document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                                } else if (document.attachEvent) {
                                    document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                                    document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                                }
                            } else {
                                onBridgeReady();
                            }

                            function onBridgeReady() {
                                WeixinJSBridge.invoke(
                                    'getBrandWCPayRequest', {
                                        "appId": res.data.data.appId,     //公众号名称，由商户传入
                                        "timeStamp": res.data.data.timeStamp,         //时间戳，自1970年以来的秒数
                                        "nonceStr": res.data.data.nonceStr, //随机串
                                        "package": res.data.data.package,
                                        "signType": "MD5",         //微信签名方式：
                                        "paySign": res.data.data.paySign //微信签名
                                    },
                                    function (res) {
                                        if (res.err_msg == "get_brand_wcpay_request:ok") {
                                            alert("购买成功");
                                            addStudy(courseId, userId, tenantId).then(res => {
                                                console.log(res.data.data);
                                                console.log(res.data.data.status);
                                                // this.$store.commit('setUser', {courseId: 0});
                                                window.location.href = "http://www.rhyun.top/#/index?tenantId=4ZMNZFG4CM"
                                            }).catch(err => {
                                                console.log(err)
                                            });
                                            // 使用以上方式判断前端返回,微信团队郑重提示：
                                            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                                        } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                                            alert("取消购买");
                                            var appid = "wxda53a4a8b2d85023"; //为测试号id
                                            var local = "http://www.rhyun.top/#/index";
                                            //不存在就打开上面的地址进行授权
                                            // window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`;
                                            window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&response_type=code&scope=snsapi_userinfo&redirect_uri=${encodeURIComponent(local)}&state=1#wechat_redirect`;
                                        }
                                    });
                            }

                        });
                        this.status = false;
                        this.$store.commit('setUser', {rate: 0})
                    }
                }
            },
            share(id) {
                //重新获取code
                if (this.$store.state.user.refresh) {
                    var local = "http://www.rhyun.top/#/buyCourse?id=" + id;
                    if (this.$store.state.user.courseId > 0) {
                        this.$store.commit('setUser', {courseId: 0})
                    }
                    this.$store.commit('setUser', {refresh: false})
                    var appid = "wxda53a4a8b2d85023";
                    //不存在就打开上面的地址进行授权
                    console.log(local);
                    window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&response_type=code&scope=snsapi_userinfo&redirect_uri=${encodeURIComponent(local)}&state=1#wechat_redirect`;
                }
            },
        }
    }
</script>

<style lang="less" scoped>
    .page {
        background-color: #F8F9FA;
        // 头部导航
        /deep/ .headerBox {
            background-color: #fff;
            border-bottom: 1px solid #eee;

            .vux-header-left {
                left: 24px;

                .vux-header-back {
                    color: #000;
                }

                .left-arrow:before {
                    border-color: #000;
                }
            }
        }

        /* 课程标题 */

        .buyTitle {
            color: #9e9fa2;
            font-size: 30px;
            background-color: #f8f9fa;
            padding: 20px 26px;
        }

        /* 课程列表 */

        .buyList {
            background-color: #fff;
            padding: 20px 26px;
            display: flex;
            align-items: center;

            .buyList_img {
                width: 312px;
                height: 184px;
                margin-right: 20px;

                img {
                    width: 100%;
                    height: 100%;
                }
            }

            .buyList_con div:nth-child(1) {
                font-size: 32px;
                margin-bottom: 40px;
            }

            .buyList_con div:nth-child(2) {
                color: #696969;
                font-size: 32px;
            }
        }

        .buyWay {
            background-color: #fff;
            padding: 20px 26px;
            display: flex;
            align-items: center;
            justify-content: center;

            img:nth-child(1) {
                width: 50px;
                height: 50px;
                margin-right: 20px;
            }

            div:nth-child(2) {
                font-size: 32px;
            }

            img:nth-child(3) {
                width: 42px;
                height: 42px;
                margin-left: auto;
            }
        }

        .buyTicket {
            background-color: #fff;
            padding: 30px 26px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-top: 24px solid #f8f9fa;
            border-bottom: 24px solid #f8f9fa;

            div {
                font-size: 30px;
            }

            img {
                width: 20px;
                height: 30px;
                margin-left: auto;
            }
        }

        /* 价格 */

        .buyPrice {
            background-color: #fff;
            padding: 50px 26px 0;
            font-size: 32px;

            .dis_flex {
                display: flex;
                align-items: center;
                justify-content: center;

                .buyPrice_auto {
                    margin-left: auto;
                }
            }

            .buyPrice_orig {
                color: #717171;
                padding: 20px 0;
            }

            .buyPrice_priv {
                color: #717171;
                padding: 20px 0;
                height: 100%;

                img {
                    width: 170px;
                    height: 64px;
                }
            }

            .buyPrice_money {
                padding: 20px 0;
                color: #000;
                font: 600 32px "微软雅黑";

                div:nth-child(2) {
                    color: #f14927;
                }
            }
        }

        .buyNow {
            color: currentColor; //router-link继承父类颜色
            width: 100%;
            height: 86px;
            line-height: 86px;
            background-color: #fa2a01;
            color: #fff;
            text-align: center;
            font-size: 34px;
            position: fixed;
            bottom: 0;
        }
    }
</style>